package com.bupt.service.project.impl;

import com.bupt.Factory.ProjectFactory;
import com.bupt.basic.Project;
import com.bupt.config.interceptor.thread.CurrentUserInfo;
import com.bupt.dao.TbProjectMapper;
import com.bupt.dto.sys.UserDto;
import com.bupt.dto.project.ProjectDto;
import com.bupt.exception.BaseException;
import com.bupt.model.TbProject;
import com.bupt.service.project.NewProjectService;
import com.bupt.utils.LocalVerify;
import com.bupt.utils.RedisUtils;
import com.bupt.utils.TokenUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("newProjectService")
public class NewProjectServiceImpl implements NewProjectService {
    @Resource
    private RedisTemplate<String, UserDto> redisTemplate;
    @Resource
    private TbProjectMapper tbProjectMapper;

    @Resource
    private CurrentUserInfo userInfo;

    //创建新项目
    @Override
    public Object createDemandProject(UserDto userDto,
                                      HttpServletRequest request,
                                      String projectName,
                                      String path) throws BaseException {
        //检测项目名称不为空
        LocalVerify.verifyString(projectName, "项目名字");
        LocalVerify.verifyString(path, "项目位置");
        synchronized (NewProjectServiceImpl.class) {
            TbProject tbProject = tbProjectMapper.selectByName(projectName);
            if (tbProject != null) throw new BaseException("项目名字重复");
            //获取当前用户
          /*  String tokenKey = TokenUtils.getTokenFromHeaderOrRequestParamOrCookie(request);
            userDto = RedisUtils.getObjectByOriKey(tokenKey, redisTemplate, UserDto.class);*/
            userDto = userInfo.getCurrentOptUser();
            Date nowTime = new Date();
            String id= UUID.randomUUID().toString().substring(0,12);
           /* SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
            String id = "P_"+sdf.format(System.currentTimeMillis());*/
            //创建project项目
            Project project = new Project(id, projectName, path);
            //将项目保存至路径下
            ProjectFactory.saveObjectDataToFile(project,project.getId(),ProjectFactory.storePath);

            //将项目基本信息存到数据库
            tbProject = new TbProject();
            tbProject.setId(id);
            tbProject.setName(projectName);
            tbProject.setCreateName(userDto.getUserName());
            tbProject.setCreatorId(userDto.getUId());
            tbProject.setManageId(null);
            tbProject.setManageName(null);
            tbProject.setGmtCreate(nowTime);
            tbProject.setPath(path);
            try {
                tbProjectMapper.insert(tbProject);
            } catch (Exception e) {
                throw new BaseException("新建项目失败" + e.getMessage());
            }
        }
        return getDemandProjects(userDto);
    }



    @Override
    public Object deleteDemandProject(UserDto userDto, String pId) throws BaseException {
        LocalVerify.verifyString(pId, "项目id");
        userDto = userInfo.getCurrentOptUser();
        TbProject tbProject = tbProjectMapper.selectByPrimaryKey(pId);
        String createName = tbProject.getCreateName();
        if (tbProject != null) {
            tbProjectMapper.deleteByPrimaryKey(pId);
            final File file = new File(ProjectFactory.storePath, pId+".project");
            if (file.exists()) {
                if(file.delete()){
                    return getDemandProjects(userDto);
                }
            }
        } else {
            throw new BaseException("不存在此项目，删除失败");
        }
        return getDemandProjects(userDto);

    }

    @Override
    public Object getDemandProject(UserDto userDto, String pId) throws BaseException {
        LocalVerify.verifyString(pId, "项目id");
        TbProject tbProject = tbProjectMapper.selectByPrimaryKey(pId);
        if(tbProject!=null){
            return tbProject;
        }else{
            throw new BaseException("不存在此项目");
        }
    }

    @Override
    public Object getDemandProjects(UserDto userDto,HttpServletRequest request) throws BaseException {
      /*  String tokenKey = TokenUtils.getTokenFromHeaderOrRequestParamOrCookie(request);
        userDto = RedisUtils.getObjectByOriKey(tokenKey, redisTemplate, UserDto.class);*/
        userDto = userInfo.getCurrentOptUser();

        return getDemandProjects(userDto);
    }
    public List<ProjectDto> getDemandProjects(UserDto userDto) throws BaseException {
        List<TbProject> tbProjects = tbProjectMapper.selectProjects();
        List<ProjectDto> projectDtos=new ArrayList<>();

        for (TbProject tbProject : tbProjects) {
            if(tbProject.getCreateName().equals(userDto.getUserName())) {
                Date date = convert(tbProject.getGmtCreate());
                ProjectDto projectDto = new ProjectDto(tbProject.getId(), tbProject.getName(), tbProject.getPath(), tbProject.getCreateName(), date);
                projectDtos.add(projectDto);
            }
        }
        return projectDtos;
    }




    public Date convert(Date date){
        DateFormat bf = new SimpleDateFormat("yyyy-MM-dd");
        Date d=null;
        try {
             d = bf.parse(bf.format(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return d;
    }

}
